import fs from 'fs-extra'
import path from 'path'
import compressing from 'compressing'

// member.xlsx
export const memberHeaders = {
  member: ['id', 'name', 'tel', 'qq', 'department', 'post', 'birthday', 'note']
}

// project.xlsx
export const projectHeaders = {
  jobs: ['id', 'job', 'mark'],
  budgets: ['type', 'detail', 'cost', 'note']
}

/**
 * 压缩/导出文件夹
 * @param {string} folderPath 文件夹路径
 * @param {string} file 压缩文件后缀(默认zip)/导出文件名
 * @param {string} targetPath 导出文件路径
 */
export const enZip = async (folderPath, file = '.zip', targetPath = '') => {
  if (folderPath === undefined || folderPath === '') throw new Error('路径缺失')
  if (!fs.pathExistsSync(folderPath)) throw new Error('路径错误')
  if (targetPath === '') {
    await compressing.zip.compressDir(folderPath, folderPath + file)
    fs.remove(folderPath)
  } else {
    if (!fs.pathExistsSync(targetPath)) throw new Error('导出路径错误')
    await compressing.zip.compressDir(folderPath, path.join(targetPath, file))
  }
}

/**
 * 解压/导入文件
 * @param {string} filePath 文件路径
 * @param {string} targetPath 导入路径
 */
export const deZip = async (filePath, targetPath = '') => {
  if (filePath === undefined || filePath === '') throw new Error('路径缺失')
  if (!fs.pathExistsSync(filePath)) throw new Error('文件路径错误')
  if (targetPath === '') {
    await compressing.zip.uncompress(filePath, path.dirname(filePath))
    fs.unlinkSync(filePath)
  } else {
    if (!fs.pathExistsSync(targetPath)) throw new Error('导入路径错误')
    await compressing.zip.uncompress(filePath, targetPath)
  }
}

/**
 * 打开目录
 * @param {string} levelPath 文件夹路径
 * @param {number} deep 深度 默认遍历
 */
export const getFolderLevel = (levelPath, deep = -1) => {
  if (deep === 0) return []
  const folder = []
  const file = []
  fs.readdirSync(levelPath).forEach((item) => {
    const filePath = path.join(levelPath, item)
    const stats = fs.statSync(filePath)
    const { ctime, birthtime } = stats
    if (stats.isDirectory()) {
      folder.push({
        label: item,
        id: filePath,
        ctime,
        birthtime,
        header: 'folder',
        children: getFolderLevel(filePath, deep - 1)
      })
    } else if (stats.isFile()) {
      file.push({
        label: item,
        id: filePath,
        ctime,
        birthtime,
        type: path.extname(item)
      })
    }
  })
  return folder.concat(file)
}
